package com.yymmarket.forum.bbs;

import java.util.List;

import com.yymmarket.forum.cache.ForumCache;
import com.yymmarket.util.SqlUtil;
import com.yymmarket.util.db.DbOperation;

/**
 * @author leihy
 * create on 2010-1-8
 */
public class BBSService {

	private static BBSService bbsService;

	private BBSService() {
	}

	public static BBSService getInstance() {
		if (bbsService == null) {
			synchronized (BBSService.class) {
				if (bbsService == null)
					bbsService = new BBSService();
			}
		}
		return bbsService;
	}
	
	private BBSDAO bbsDao = new BBSDAO();
	
	
	public boolean addBBSBean(BBSBean bean) {
		
		if(this.bbsDao.addBBSBean(bean)) {
			this.getBBSBeanById(bean.getId());
			return true;
		} else {
			return false;
		}
		
		
	}
	
	public BBSBean getBBSBeanById(int id) {
		
		BBSBean bean = ForumCache.bbsCache.get(id);
		
		if(bean == null) {
			bean = this.bbsDao.getBBSBeanById(id);
			if(bean != null)
				ForumCache.bbsCache.put(id, bean);
		}
		
		if(bean.getTotalCounter()>=BBSBean.TOTAL_UPDATE||bean.getTodayCounter()>=BBSBean.TODAY_UPDATE) {
			synchronized(bean) {
				if(bean.getTotalCounter()>=BBSBean.TOTAL_UPDATE||bean.getTodayCounter()>=BBSBean.TODAY_UPDATE) {
					this.updateBBSTotalToday(bean.getTotalCounter(), bean.getTodayCounter(), id);
					bean.reset();
				}
			}
		}
		
		return bean;
	}
	
	public List<BBSBean> getBBSList() {
		return this.bbsDao.getBBSBeanList(" type = 0");
	}
	
	public boolean deleteBBSById(int id) {
		return SqlUtil.executeUpdate("delete from forum_bbs where id = " +id, DbOperation.DB_WAP);
	}
	
	public boolean updateBBSTotalToday(int total,int today,int id) {
		return this.bbsDao.updateBBSTotalToday(total, today, id);
	}
}
